<?php
/**
 * Author: top-songshijie
 * DateTime: 2020/03/22 22:35
 */

namespace SwoPhp\Server\WebSocket;

use SwoPhp\Server\Http\HttpServer;
use Swoole\WebSocket\Server as SwooleServer;

class WebSocketServer extends HttpServer
{
    public function initSetting()
    {
        $config       = app('config');
        $this->port   = $config->get('server.websocket.port');
        $this->host   = $config->get('server.websocket.host');
        $this->config = $config->get('server.websocket.swoole');
    }

    public function createServer()
    {
        $this->swooleServer = new SwooleServer($this->host, $this->port);
        echo "
                               SERVER INFORMATION
********************************************************************************
* WEBSOCKET     | Listen: {$this->host}:{$this->port}
********************************************************************************
        ";
    }

    public function initEvent()
    {
        $this->setEvent('sub', [
            'open'    => 'onOpen',
            'message' => 'onMessage',
            'close'   => 'onClose',
        ]);
    }

    public function onOpen(SwooleServer $server, $request)
    {
        Connections::init($request->fd,$request->server['path_info']);

        app('route')->setFlag('WebSocket')->setMethod('open')->match($request->server['request_uri'],[$server, $request]);
    }

    public function onMessage(SwooleServer $server, $frame)
    {
        $path = (Connections::get($frame->fd))['path'];

        app('route')->setFlag('WebSocket')->setMethod('message')->match($path,[$server, $frame]);
    }

    public function onClose(SwooleServer $server, $fd)
    {
        $path = (Connections::get($fd))['path'];

        app('route')->setFlag('WebSocket')->setMethod('close')->match($path,[$server, $fd]);

        Connections::destory($fd);
    }

}
